package com.atguigu.study.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

//100个线程，每个线程加100次，求最后的number值
public class CASDemo {
 private int number;

    public int getNumber() {
        return number;
    }

    public void setNumber() {
        ++number;
    }
    public AtomicInteger atomicInteger=new AtomicInteger();

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.getAndIncrement();
       atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        CASDemo casDemo = new CASDemo();
        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 100; i1++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
            },String.valueOf(i)).start();
            countDownLatch.countDown();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t"+casDemo.getNumber());
        System.out.println(Thread.currentThread().getName()+"\t"+casDemo.getAtomicInteger().get());
    }
}
